<template>
    <el-form :model="categoryForm" label-width="100px" :rules="rules" ref="cForm" v-loading="loading">
        <el-form-item label="分类名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="small" plain @click="save()">保存</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    import { get, post } from '@/plugins/axios.js'
    import { url } from './api.js'
    import store from '@/store/index.js'
    export default {
        name: 'CategoryEdit',
        props: ['id', 'parentId', 'level'],
        created() {
            if(this.id) {
                this.categoryForm.id = this.id
                this.getById()
            } else {
                this.categoryForm.parentId = this.parentId
                this.categoryForm.level = this.level
            }
        },
        data() {
            return {
                categoryForm: {
                    name: '',
                },
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入分类名称',
                            trigger: 'blur',    
                        },
                        {
                            max: 20,
                            message: '分类名称最多输入20个字符',
                            trigger: 'blur',    
                        }, 
                    ]
                }
            }
        },
        computed: {
            loading () {
                return store.getters.GET_LOADING
            }
        },
        methods: {
            save() {
                this.$refs.cForm.validate(valid => {
                    if (valid) {
                        post(this.id === null ? url.add : url.update, this.categoryForm, content => {
                            this.$emit('update:show', false)
                            this.$emit('getCategoryData')
                        })
                    }
                })
            },
            getById() {
                get(url.getById, {id: this.id}, content => {
                    for (const key in this.categoryForm) {
                        if(Object.hasOwnProperty.call(content, key)) {
                            this.categoryForm[key] = content[key]
                        }
                    }
                })
            }
        }
    }
</script>

<style scoped lang="less">
    .el-input {
        width: 85%;
    }
    /deep/ .el-form-item__content {
        text-align: center;
    }
    .el-radio-group {
        position: relative;
        left: -5%;
    }
    .el-button {
        position: relative;
        left: -9%;
    }
</style>